import React, {Component} from 'react';
import {Table, Button, Input, message, InputNumber} from 'antd';
import {API_URL, contractColumn, invoiceColumn} from "../constants";
import {getCrmRecordFromSql, isBlank} from "../util/util";
import InvoiceTable from './InvoiceTable'

const ZOHO = window.ZOHO;

class InvoiceDetail extends Component {
    constructor(props) {
        super(props);
        this.InvoiceTableRef = React.createRef()
        console.log(props)
        this.state = {
            contractData: [],
            contractColumn: contractColumn,
            selectedRows: [],
            invoiceDatas: [],
            scrollWidth: contractColumn.length * 200,
            fcontractNo: props.FcontractNo,
            selectedData: [],
            formData: props.formData,
        };
    }

    componentDidMount() {
        console.log('componentDidMount')
        const {fcontractNo} = this.state
        if (fcontractNo !== undefined) {
            let fcontractNoID = fcontractNo.map(item => item.key);
            let contractDatas = [];
            let apinames = contractColumn.map(column => column.dataIndex);
            getCrmRecordFromSql(`select ${apinames} from Foreignsacontractdetail where Foreignsacontract.id in (${fcontractNoID})`).then(data => {
                data?.forEach(item => {
                    let contractData = {};
                    contractColumn.forEach(column => {
                        contractData[column.dataIndex] = item[column.dataIndex];
                    })
                    contractData['key'] = item['id']
                    contractDatas.push(contractData)
                })
                this.setState({contractData: contractDatas})
            });
        }
    }


    handleCellChange = (newValue, field, index) => {
        const {invoiceDatas} = this.state;

        const newData = [...invoiceDatas];
        if (field.data_type === "text" || field.data_type === "double" || field.data_type === "integer" || field.data_type === "textarea") {
            newData[index]['Name'] = newValue;
        }

        if (field.data_type === "lookup") {
            newData[index][field.api_name] = {
                id: newValue.value,
                name: newValue.label
            }
        }

        this.setState({
            data: newData,
        });
    };

    handleTransfer = () => {
        const {contractData, selectedRows} = this.state;
        const updatedData = contractData.filter((item) => selectedRows.includes(item.key));
        const unselectedData = contractData.filter((item) => !selectedRows.includes(item.key));
        let invoiceDatas = this.InvoiceTableRef.current.getInvoiceDatas();

        console.log(updatedData)
        let datas = [];
        updatedData.forEach((item) => {
            let invoiceData = {
                Name: invoiceDatas.length + 1,
                AccountOrderNo: item.AccountOrderNo,
                Product: item['Product.Product_Name'],
                ProductId: item['Product.id'],
                AccountprtNo: item.AccountprtNo,
                internalcode: item.internalcode,
                Productname: item.Productname,
                Chinesespecification: item.Chinesespecification,
                Ptrequirements_material: item.Chptrequirements_material,
                Chineseingredients: item.Chineseingredients,
                Make: item.Brand,
                Englishname: item.Englishname,
                Specification: item.Specification,
                Unit: item.Unit,
                Nuofboxesinpg: item.Nuofboxesinpg,
                Nuofboxeinnerbox: item.Nuofboxeinnerbox,
                Lengthofouterbox: item.Lengthofouterbox,
                Heightofouterbox: item.Heightofouterbox,
                Grossweight: item.Grossweight,
                PackQty: item.NumberofCartons,
                TotalGrossweight: item.TotalGrossWeight,
                TotalVolume: item.TotalVolume,
                Packaginunit: item.Packaginunit,
                Cartonwidth: item.Cartonwidth,
                Netweight: item.Netweight,
                Volume: item.Volume,
                TotalNetweight: item.TotalNetWeight,
                Foreignsacontract: item['Foreignsacontract.Name'],
                key: item.key,
                Quantity: item.ABQuantity,
                Purchaseunitprice: item.Unit_Price,
                PurchaseQty: item.ABQuantity,
                Packagingquantityperpg: item.QuantityperCarton,
            };
            datas.push(invoiceData)
        })
        console.log(datas)
        invoiceDatas = invoiceDatas.concat(datas);
        this.setState({
            selectedData: updatedData,
            invoiceDatas: invoiceDatas,
            contractData: unselectedData,
            selectedRows: [],
        }, () => {
            // 在setState的回调函数中，将更新后的invoiceDatas传递给子组件
            this.InvoiceTableRef.current.updateInvoiceDatas(invoiceDatas, updatedData);
        });
    };

    updatecontractData = (newData) => {
        const {contractData} = this.state

        let a = [...contractData]
        newData.forEach(item => {
            a.push(item)
        })
        this.setState({
            contractData: a,
            selectedRows: []
        });
    }


    handleCancel = () => {
        // 处理取消逻辑
        // ...
        console.log('取消');
    };
    handleSave = () => {
        const {formData} = this.state
        formData.validateFields().then((values) => {
            values.ContractDate = values.ContractDate?.format('YYYY-MM-DD');
            values.Deliverytime = values.Deliverytime?.format('YYYY-MM-DD');

            values.Account = {
                id: values.Account?.value,
                name: values.Account?.label
            }
            values.Currencys = {
                id: values.Currencys?.value,
                name: values.Currencys?.label
            }
            values.Plant = {
                id: values.Plant?.value,
                name: values.Plant?.label
            }
            values.ShipperInformation = {
                id: values.ShipperInformation?.value,
                name: values.ShipperInformation?.label
            }
            values.States = {
                id: values.States?.value,
                name: values.States?.label
            }
            values.FcontractNo?.map(item => {
                item.field1 = {
                    id: item.key
                }
            })

            let req_data = {
                "headers": {},
                "url": API_URL + `/crm/v3/PSNotice`,
                "param_type": 2
            };
            if (window.id !== undefined) {
                req_data.method = "PUT";
                values.id = window.id;
            } else {
                req_data.method = "POST";
            }
            req_data.parameters = {
                data: [values]
            }
            let invoiceData = this.InvoiceTableRef.current.state.data;
            ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                let id = data.details.statusMessage.data[0].details.id;
                console.log(id)
                console.log(invoiceData)
                let contractQtys = [];
                invoiceData.map(item => {
                    item.PSNotice = {
                        id: id,
                        name: values.Name
                    }
                    if (window.id === undefined) {
                        item.Product = {
                            id: item.ProductId,
                            Product_Name: item.Productname,
                        }
                        item.Foreignsacontractdetail = {
                            id: item.key,
                            Name: item.Name
                        }
                    }

                    item.Name = item.Name + "";
                    if (isBlank(item.id)) {
                        delete item.id;
                    }
                    contractQtys.push({
                        "id": item.key,
                        "ABQuantity": item.Quantity,
                    })
                })
                let req_data = {
                    "parameters": {
                        data: invoiceData
                    },
                    "headers": {},
                    "url": API_URL + `/crm/v3/PSNoticedetail`,
                    "param_type": 2
                };
                if (window.id !== undefined) {
                    req_data.method = "PUT";
                } else {
                    req_data.method = "POST";
                }
                ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                    console.log(data);
                });
                message.success("保存成功");
                ZOHO.CRM.UI.Record.open({Entity: "PSNotice", RecordID: id})
                    .then(function (data) {
                        console.log(data)
                        req_data = {
                            "parameters": {
                                data: contractQtys
                            },
                            "headers": {},
                            "method": "PUT",
                            "url": API_URL + `/crm/v3/Foreignsacontractdetail`,
                            "param_type": 2
                        };
                        ZOHO.CRM.CONNECTION.invoke("crm", req_data).then(function (data) {
                            console.log(data);
                        });
                    })
            });
        }).catch(e => {
            console.log(e)
            e.errorFields.forEach(errors => {
                message.error(errors.errors)
            })
        })

    };

    onRowChange = (selectedRows) => {
        console.log(selectedRows)
        this.setState({selectedRows});
    }

    render() {
        const {contractData, selectedRows, invoiceDatas, contractColumn, scrollWidth, selectedData} = this.state;


        return (
            <div>
                <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: 16}}>
                    <Button type="primary" onClick={this.handleSave}>
                        保存
                    </Button>
                    <Button style={{marginLeft: 8}} onClick={this.handleCancel}>
                        取消
                    </Button>
                </div>
                <div>
                    <InvoiceTable ref={this.InvoiceTableRef}
                                  dataSource={invoiceDatas}
                                  selectedData={selectedData}
                                  moduleName="PSNoticedetail"
                                  parentModuleName="PSNotice"
                                  updatecontractData={this.updatecontractData}
                                  paste={false}/>

                </div>
                <div>
                    <div style={{
                        display: 'flex',
                        justifyContent: 'flex-end',
                        marginBottom: 16,
                        marginTop: 16,
                        marginRight: 16
                    }}>
                        <Button type="primary" onClick={this.handleTransfer}>
                            确定
                        </Button>
                    </div>
                    <Table dataSource={contractData} columns={contractColumn} rowSelection={{
                        fixed: true,
                        selectedRowKeys: selectedRows, // 多选表格选中行的 keys 数组
                        onChange: this.onRowChange, // 选中行发生变化时的回调函数
                    }}
                           scroll={{y: 240, x: scrollWidth}}>

                    </Table>
                </div>

            </div>
        );
    }
}

export default InvoiceDetail;